package com.yangguang.huahui.ui.activitys;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.netease.scan.IScanModuleCallBack;
import com.netease.scan.QrScan;
import com.netease.scan.ui.CaptureActivity;
import com.yangguang.huahui.Config;
import com.yangguang.huahui.R;
import com.yangguang.huahui.easemob.AppHelper;
import com.yangguang.huahui.entity.DataInfo;
import com.yangguang.huahui.ui.adapters.TypePageAdapter;
import com.yangguang.huahui.ui.fragments.BaseFragment;
import com.yangguang.huahui.ui.fragments.FindFragment;
import com.yangguang.huahui.ui.fragments.FirstFragment;
import com.yangguang.huahui.ui.fragments.MessageFragment;
import com.yangguang.huahui.ui.fragments.MyFragment;
import com.yangguang.huahui.utils.CommonUtil;
import com.yangguang.huahui.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnCheckedChanged;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {
    private ArrayList<BaseFragment> fragments;
    private int tab;
    int msg_count;

    @BindView(R.id.main_bottom_tabs)
    RadioGroup group;
    @BindView(R.id.main_home)
    RadioButton main_home;
    @BindView(R.id.main_find)
    RadioButton main_fujin;
    @BindView(R.id.main_message)
    RadioButton main_message;
    @BindView(R.id.main_my)
    RadioButton main_my;
    private int[] checkid = {R.id.main_home, R.id.main_find, R.id.main_message, R.id.main_my};
    @BindView(R.id.tv_dot)
    TextView tv_dot;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            setDot();
        }
    };
    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            for (EMMessage message : messages) {
                AppHelper.getInstance().getNotifier().onNewMsg(message);
            }
            LogUtil.e("----->onMessageReceived", true);
            handler.postDelayed(runnable, 0);
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {

        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };

    private void setDot() {
        msg_count = getUnreadMsgCountTotal();
        if (msg_count > 0) {
            findViewById(R.id.tv_dot).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.tv_dot).setVisibility(View.GONE);
        }
    }

    /**
     * get unread message count
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMessageCount();
        return unreadMsgCountTotal;
    }


    @Override
    protected int initLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        tab = getIntent().getIntExtra("home_tab", 0);
        fragments = getFragments();
        replaceFragment(FirstFragment.newInstance(getString(R.string.home)));
        main_home.setChecked(true);
    }

    /**
     * 设置默认的
     */
    private void replaceFragment(Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.layFrame, fragment);
        transaction.commit();
    }
    private void replaceFragment(int postition) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.layFrame, fragments.get(postition));
        transaction.commit();
    }

    private ArrayList<BaseFragment> getFragments() {
        ArrayList<BaseFragment> fragments = new ArrayList<>();
        fragments.add(FirstFragment.newInstance(getString(R.string.home)));
        fragments.add(FindFragment.newInstance(getString(R.string.find)));
        fragments.add(MessageFragment.newInstance(getString(R.string.message)));
        fragments.add(MyFragment.newInstance(getString(R.string.mine)));
        return fragments;
    }

    @Override
    protected void initData() {
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        group.setOnCheckedChangeListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        handler.postDelayed(runnable, 200);
        if (DataInfo.LOGOUT.equals("logout")) {
            tab = 0;
            DataInfo.LOGOUT = "";
        }
        setChecked((RadioButton) findViewById(checkid[tab]));
    }


    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.main_home:
                tab = 0;
                replaceFragment(0);
                break;
            case R.id.main_find:
                tab = 1;
                replaceFragment(1);
                break;
            case R.id.main_message:
                if (CommonUtil.isNull(DataInfo.TOKEN)) {
                    tab = 0;
                    startActivity(new Intent(mContext, LoginActivity.class));
                    finish();
                    return;
                }
                tab = 2;
                replaceFragment(2);
                break;
            case R.id.main_my:
                if (CommonUtil.isNull(DataInfo.TOKEN)) {
                    tab = 0;
                    startActivity(new Intent(mContext, LoginActivity.class));
                    finish();
                    return;
                }
                tab = 3;
                replaceFragment(3);
                break;
            default:
                break;
        }
    }

    private void setChecked(RadioButton radioButton) {
        radioButton.setChecked(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.INPUT_REQUEST_CODE && resultCode == Config.INPUT_RESULT_CODE) {
            tab = getIntent().getIntExtra("home_tab", 0);
            replaceFragment(tab);
        }
    }

    @Override
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);
        startQRCode();
    }

    public void startQRCode() {
        QrScan.getInstance().launchScan(mContext, new IScanModuleCallBack() {
            @Override
            public void OnReceiveDecodeResult(final Context context, String result) {
                AlertDialog dialog = new AlertDialog.Builder(context)
                        .setMessage(result)
                        .setCancelable(false)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                QrScan.getInstance().restartScan((CaptureActivity) context);
                            }
                        })
                        .setPositiveButton("关闭", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                QrScan.getInstance().finishScan((CaptureActivity) context);
                            }
                        })
                        .create();
                dialog.show();
            }
        });
    }
}
